package alp.starcode.nudtportal.framework.util;

import alp.starcode.nudtportal.framework.config.rabbitmq.ExchangeAndQueueConfig;
import alp.starcode.nudtportal.framework.login.user.User;
import alp.starcode.nudtportal.framework.mybatis.dao.impl.LogDataExchangeContentDaoImpl;
import alp.starcode.nudtportal.framework.mybatis.dao.impl.LogDataExchangeDaoImpl;
import alp.starcode.nudtportal.framework.mybatis.dto.LogDataExchangeDTO;
import alp.starcode.nudtportal.framework.mybatis.dto.SendDTO;
import alp.starcode.nudtportal.framework.mybatis.entity.LogDataExchange;
import alp.starcode.nudtportal.framework.mybatis.entity.LogDataExchangeContent;
import alp.starcode.nudtportal.framework.mybatis.vo.LogDataExchangeVO;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * 发送mq相关工具类
 *
 * @Author wj
 * @Date 2023/8/15 14:14
 */
@Component
@Slf4j
public class MQUtils {
    @Qualifier("getCachingConnectionFactory")
    @Autowired
    private ConnectionFactory connectionFactory;
    @Autowired
    private ExchangeAndQueueConfig exchangeAndQueueConfig;
    @Autowired
    LogDataExchangeDaoImpl logDataExchangeDao;
    @Autowired
    LogDataExchangeContentDaoImpl logDataExchangeContentDao;
    @Autowired
    ElasticsearchRestTemplate restTemplate;
    @Value("${mq.serviceCode}")
    public String serviceCode;

    public RabbitTemplate getRabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMandatory(true);
        return template;
    }

    public Boolean sendDirect(String exchange, String routingKey, String queueName, String msg) {
        try {
        //创建绑定关系
        exchangeAndQueueConfig.createDirectBindQueue(exchange, routingKey, queueName);

        //发送消息
        RabbitTemplate rabbitTemplate = getRabbitTemplate(connectionFactory);

        Message message = MessageBuilder
                .withBody(msg.getBytes())
                .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                .setContentEncoding("UFT-8")
                .setMessageId(UUID.randomUUID().toString()).build();

            rabbitTemplate.send(exchange, routingKey, message);
            return true;
        } catch (AmqpException e) {
            log.error("发送mq消息失败:{}", e.getMessage());
            return false;
        }

    }

    /**
     * 数据转换成mq消息格式
     */
    public String constructSend(String dataType, String content,Long sendTime, String reserve) {
        SendDTO sendDTO = new SendDTO();
        sendDTO.setDataType(dataType);
        sendDTO.setSendTime(sendTime);
        sendDTO.setReserve(reserve);
        sendDTO.setContent(content);
        sendDTO.setServiceCode(serviceCode);
        String string = JSON.toJSONString(sendDTO);
        return string;
    }

    /**
     * 添加消息队列日志
     * @param user 当前用户
     * @param type 交换类型
     * @param data 加密数据
     * @param isSuccess false失败，true成功
     * @param sendTime 交换时间
     */
    @Transactional(rollbackFor = Exception.class)
    public void addLogExchange(User user, String type, String data, Boolean isSuccess, Long sendTime) {
        //写入消息队列日志
        LogDataExchange logDataExchange = new LogDataExchange();
        logDataExchange.setExchangeId(UUID.randomUUID().toString());
        logDataExchange.setUserId(user.getUserId());
        logDataExchange.setCampusNumber(user.getCampusNumber());
        logDataExchange.setLoginName(user.getLoginAccount());
        logDataExchange.setExchangeType(type);
        logDataExchange.setExchangeTime(sendTime);
        logDataExchange.setExchangeStatus(isSuccess ? 1 : 0);
        long timeMillis = System.currentTimeMillis();
        logDataExchange.setCreateTime(timeMillis);
        logDataExchange.setUpdateTime(timeMillis);
        logDataExchangeDao.save(logDataExchange);
        LogDataExchangeContent logDataExchangeContent = new LogDataExchangeContent();
        logDataExchangeContent.setExchangeId(logDataExchange.getExchangeId());
        //赋值
        logDataExchangeContent.setExchangeData(data);
        logDataExchangeContent.setCreateTime(timeMillis);
        logDataExchangeContent.setUpdateTime(timeMillis);
        logDataExchangeContentDao.save(logDataExchangeContent);
        LogDataExchangeDTO logDataExchangeDTO = BeanUtils.copyBean(logDataExchange, LogDataExchangeDTO.class);
        logDataExchangeDTO.setExchangeData(data);
        //写入es
        addLogExchangeWord(logDataExchangeDTO);
    }

    /**
     * 添加到es文档
     */
    private void addLogExchangeWord(LogDataExchangeDTO logDataExchangeDTO) {
        try {
            LogDataExchangeVO logDataExchangeVO = BeanUtils.copyProperties(logDataExchangeDTO, LogDataExchangeVO.class);
            restTemplate.save(logDataExchangeVO);
        } catch (Exception e) {
            log.error("添加es文档失败：{}", e.getMessage());
        }
    }
}
